package com.ct.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import com.ct.entity.enums.PageSize;
import com.ct.entity.po.User;
import com.ct.entity.query.SimplePage;
import com.ct.entity.query.UserQuery;
import com.ct.entity.vo.PaginationResultVO;
import com.ct.entity.vo.UserVO;
import com.ct.exception.BusinessException;
import com.ct.mappers.UserMapper;
import com.ct.service.UserService;
import com.ct.utils.CopyTools;
import com.ct.utils.MD5Utils; // 引入 MD5 工具类
import com.ct.utils.StringTools;

import jakarta.annotation.Resource;

/**
 * 用户表 业务接口实现
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper<User, UserQuery> userMapper;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<User> findListByParam(UserQuery param) {
        return this.userMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserQuery param) {
        return this.userMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<User> findListByPage(UserQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<User> list = this.findListByParam(param);
        PaginationResultVO<User> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(),
                page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(User bean) {
        return this.userMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<User> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<User> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(User bean, UserQuery param) {
        StringTools.checkParam(param);
        return this.userMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserQuery param) {
        StringTools.checkParam(param);
        return this.userMapper.deleteByParam(param);
    }

    /**
     * 根据UserId获取对象
     */
    @Override
    public User getUserByUserId(String userId) {
        return this.userMapper.selectByUserId(userId);
    }

    /**
     * 根据UserId修改
     */
    @Override
    public Integer updateUserByUserId(User bean, String userId) {
        return this.userMapper.updateByUserId(bean, userId);
    }

    /**
     * 根据UserId删除
     */
    @Override
    public Integer deleteUserByUserId(String userId) {
        return this.userMapper.deleteByUserId(userId);
    }

    /**
     * 登录
     */
    @Override
    public UserVO login(String position, String userId, String password) {
        User user = this.userMapper.selectByUserId(userId);

        if (null == user) {
            throw new BusinessException("用户不存在");
        }

        if (!position.equals(user.getPosition())) {
            throw new BusinessException("职位错误");
        }
        // 对输入的密码进行 MD5 加密
        String encryptedPassword = MD5Utils.md5(password);
        System.out.println("前端传过来的密码" + password);
        System.out.println(encryptedPassword);
        if (!user.getPassword().equals(encryptedPassword)) {
            throw new BusinessException("密码错误");
        }

        UserVO userVo = CopyTools.copy(user, UserVO.class);

        // 计算年龄
        LocalDate birthDate = user.getBirthday().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(birthDate, currentDate).getYears();
        userVo.setAge(String.valueOf(age));

        return userVo;
    }

    @Override
    public List<User> getAllUsersByIdList(List<String> userIdList) {
        ArrayList<User> userList = new ArrayList<>();
        for (String userId : userIdList) {
            User user = this.getUserByUserId(userId);
            if (null != user) {
                userList.add(user);
            }
        }
        return userList;
    }

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(Map<String, Object> message) throws InterruptedException {
        System.out.println("userId: " + message.get("userId"));
        System.out.println("message: " + message.get("message"));
        messagingTemplate.convertAndSend("/topic/travelRequests", message);
    }

    @RabbitListener(queues = "travelApply.queue") // 审批记录更新消息队列
    public void listenApprovalMessage(Map<String, Object> message) {
        messagingTemplate.convertAndSend("/topic/approvalMessage", message);
    }

    /**
     * 经理审批出差申请, 提醒财务人员和员工
     */
    @RabbitListener(queues = "approve.travel")
    public void listenApproveTravelApply(Map<String, Object> message) throws InterruptedException {
        System.out.println("listenApproveTravelApply");
        messagingTemplate.convertAndSend("/topic/approveTravelApply", message);
    }

    /**
     * 财务审批预支款申请, 提醒员工
     */
    @RabbitListener(queues = "approve.advance")
    public void listenApproveAdvanceApply(Map<String, Object> message) throws InterruptedException {
        System.out.println("listenApproveAdvanceApply");
        messagingTemplate.convertAndSend("/topic/approveAdvanceApply", message);
    }

    /**
     * 经理审批报销申请, 提醒财务人员和员工
     */
    @RabbitListener(queues = "approve.reimbursementMa")
    public void listenApproveReimbursementMaApply(Map<String, Object> message) throws InterruptedException {
        System.out.println("listenApproveReimbursementMaApply");
        messagingTemplate.convertAndSend("/topic/approveReimbursementMaApply", message);
    }

    /**
     * 经理审批报销申请, 提醒财务人员和员工
     */
    @RabbitListener(queues = "approve.reimbursementFi")
    public void listenApproveReimbursementFiApply(Map<String, Object> message) throws InterruptedException {
        System.out.println("listenApproveReimbursementFiApply");
        messagingTemplate.convertAndSend("/topic/approveReimbursementFiApply", message);
    }

}
